package com.pur.zsms.company.service.impl;

import java.util.List;

import javax.annotation.Resource;

import net.sf.cglib.beans.BeanCopier;

import org.springframework.stereotype.Service;

import com.pur.zsms.common.exception.GenericException;
import com.pur.zsms.common.support.PageController;
import com.pur.zsms.common.support.PaginationSupport;
import com.pur.zsms.company.dao.ICompanyDao;
import com.pur.zsms.company.po.CompanyPo;
import com.pur.zsms.company.po.CompanySupPo;
import com.pur.zsms.company.service.ICompanyService;
import com.pur.zsms.company.vo.CompanyVo;

@Service("companyService")
public class CompanyServiceImpl implements ICompanyService {

	String msg = "";

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	@Resource(name = "companyDao")
	private ICompanyDao companyDao;

	public PaginationSupport listCompany(PageController pageController, CompanyVo companyVo) throws GenericException {
		return companyDao.listCompany(pageController, companyVo);
	}

	public PaginationSupport listCompanyForSup(PageController pageController, CompanyVo companyVo) throws GenericException {
		return companyDao.listCompanyForSup(pageController, companyVo);
	}

	public boolean addCompany(CompanyVo c) throws GenericException {

		// 检查同名公司
		List<CompanyPo> list = companyDao.getCompanyPo(c);
		if (list != null && list.size() > 0) {
			msg = "已录入同名公司,请查看以录公司！";
			return false;
		}

		String[] permissionString = c.getPermissionString().split(",");

		CompanyPo po = new CompanyPo();
		BeanCopier copier = BeanCopier.create(CompanyVo.class, CompanyPo.class, false);
		copier.copy(c, po, null);

		for (String permission : permissionString) {
			if (permission.equals("1")) {
				po.setShopFlag("1");
			} else if (permission.equals("2")) {
				po.setSupFlag("1");
			}
		}

		companyDao.addCompanyPo(po);
		return true;
	}

	public boolean saveCompanyForSup(CompanyVo c) throws GenericException {
		// 检查同名公司
		List<CompanyPo> list = companyDao.getCompanyPo(c);
		if (list != null && list.size() > 0) {
			msg = "已录入同名公司,请查看以录公司！";
			return false;
		}

		String[] permissionString = c.getPermissionString().split(",");

		CompanyPo po = new CompanyPo();
		BeanCopier copier = BeanCopier.create(CompanyVo.class, CompanyPo.class, false);
		copier.copy(c, po, null);

		for (String permission : permissionString) {
			if (permission.equals("1")) {
				po.setShopFlag("1");
			} else if (permission.equals("2")) {
				po.setSupFlag("1");
			}
		}

		companyDao.addCompanyPo(po);
		// 插入公司供货商关系表
		CompanySupPo companySupPo = new CompanySupPo();
		companySupPo.setCompanyId(po.getCompanyId());
		companySupPo.setSupId(c.getSupId());
		companyDao.addCompanySupPo(companySupPo);

		return true;
	}

}
